#define _CRT_SECURE_NO_WARNINGS	

typedef int DataType;
typedef struct QueueNode
{
	DataType data;
	struct QueueNode* next;
}QueueNode;

typedef struct Queue
{
	QueueNode* phead;
	QueueNode* ptail;
	int size;
}Queue;

void Init_Queue(Queue* pq)
{
	assert(pq);
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

bool Empty_Queue(Queue* pq)
{
	assert(pq);
	return pq->phead == NULL;
}

void Destory_Queue(Queue* pq)
{
	assert(pq);
	QueueNode* pcur = pq->phead;
	while (pcur)
	{
		QueueNode* next = pcur->next;
		free(pcur);
		pcur = NULL;
		pcur = next;
	}
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

void Push_Queue(Queue* pq, DataType x)
{
	assert(pq);
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (!newnode)
	{
		perror("malloc fail!");
		exit(1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (!pq->phead)
	{
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = pq->ptail->next;
	}
	pq->size++;
}

void Pop_Queue(Queue* pq)
{
	assert(!Empty_Queue(pq));
	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else
	{
		QueueNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	pq->size--;
}

DataType Get_Head_Queue(Queue* pq)
{
	assert(!Empty_Queue(pq));
	return pq->phead->data;
}

DataType Get_Tail_Queue(Queue* pq)
{
	assert(!Empty_Queue(pq));
	return pq->ptail->data;
}

int Size_Queue(Queue* pq)
{
	return pq->size;
}

typedef struct
{
	Queue q1;
	Queue q2;
} MyStack;


MyStack* myStackCreate()
{
	MyStack* st = (MyStack*)malloc(sizeof(MyStack));
	Init_Queue(&st->q1);
	Init_Queue(&st->q2);
	return st;
}

void myStackPush(MyStack* obj, int x)
{
	if (!Empty_Queue(&obj->q1))
		Push_Queue(&obj->q1, x);
	else
		Push_Queue(&obj->q2, x);
}

int myStackPop(MyStack* obj)
{
	Queue* emp = &obj->q1;
	Queue* noemp = &obj->q2;
	if (Empty_Queue(&obj->q2))
	{
		emp = &obj->q2;
		noemp = &obj->q1;
	}
	while (Size_Queue(noemp) > 1)
	{
		Push_Queue(emp, Get_Head_Queue(noemp));
		Pop_Queue(noemp);
	}
	int top = Get_Head_Queue(noemp);
	Pop_Queue(noemp);
	return top;
}

int myStackTop(MyStack* obj)
{
	if (!Empty_Queue(&obj->q1))
		return Get_Tail_Queue(&obj->q1);
	return Get_Tail_Queue(&obj->q2);
}

bool myStackEmpty(MyStack* obj)
{
	if (Empty_Queue(&obj->q1) && Empty_Queue(&obj->q2))
		return true;
	return false;
}

void myStackFree(MyStack* obj)
{
	Destory_Queue(&obj->q1);
	Destory_Queue(&obj->q2);
	free(obj);
	obj = NULL;
}